package com.bright.hxj.cwduijie.service.impl;

import com.bright.hxj.cwduijie.enums.DataApi;
import com.bright.hxj.cwduijie.pojo.bo.ApiDataCollection;
import com.bright.hxj.cwduijie.pojo.dto.AssistCodeDto;
import com.bright.hxj.cwduijie.pojo.po.AssistCode;
import com.bright.hxj.cwduijie.pojo.query.DuijieQuery;
import com.bright.hxj.cwduijie.repository.AssistCodeRepository;
import com.bright.hxj.cwduijie.service.AbstractPerThousandApiService;
import com.bright.ghj.common.util.ListUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;

/**
 * @Author hxj
 * @Date 2024/7/29 16:25
 * @Description
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class ApiAssistCodeServiceImpl extends AbstractPerThousandApiService<AssistCode> {

    private final AssistCodeRepository repo;

    @Override
    public JpaSpecificationExecutor getJpaSpecificationExecutor() {
        return repo;
    }

    @Override
    public DataApi getDataApi() {
        return DataApi.ASSIST_CODE;
    }

    @Override
    public Function<AssistCode, Integer> getIdFunc() {
        return AssistCode::getID;
    }

    @Override
    public Function<AssistCode, String> getDataKeyFunc() {
        return AssistCode::getDATA_KEY;
    }

    @Override
    public Function<ApiDataCollection, List<AssistCode>> getDataFunc() {
        return ApiDataCollection::getAssistCodes;
    }

    @Override
    public boolean isExistsTYSHXYDMField() {
        return false;
    }

    @Override
    public DataApi getDeleteDataApi() {
        return DataApi.DELETE_ASSIST_CODE;
    }


    @Override
    protected void getData(ApiDataCollection apiDataCollection, DuijieQuery duijieQuery) {
//        List<AssistCode> assets = repo.findAll(getDataQuerySpecification(OpType.ADD_OR_EDIT.getValue(), duijieQuery.getZtDataKey()));
//        List<AssistCode> codes = repo.getByZtDataKeyAndOpTypeAndSjjhbz(duijieQuery.getZtDataKey(), OpType.ADD_OR_EDIT.getValue(), Arrays.asList(SJJHBZ.WAITING.getValue(), SJJHBZ.ERROR.getValue()));
        apiDataCollection.setAssistCodes(getNeedDuijieData(duijieQuery));
    }

    @Override
    public void sendData(ApiDataCollection apiDataCollection, DuijieQuery duijieQuery, String batchId) throws JsonProcessingException {
        // 由于建表的时候主表子表建成了一张表 所以发送数据的时候要另外打包
        List<AssistCode> codes = getDataFunc().apply(apiDataCollection);

        List<AssistCodeDto> dataList = new ArrayList<>();

        Map<String, List<Map<String, String>>> assistCodeMap = new HashMap<>(); // key=辅助核算项目编码  value=自定义字段集合
        for (AssistCode type : codes) {
            if (!assistCodeMap.containsKey(type.getFZHS_PROJECT_BM())) {
                List<Map<String, String>> assistFieldsList = new ArrayList<>();
                assistCodeMap.put(type.getFZHS_PROJECT_BM(), assistFieldsList);
                AssistCodeDto assistCodeDto = new AssistCodeDto();
                assistCodeDto.setDATA_KEY(type.getDATA_KEY());
                assistCodeDto.setZT_DATA_KEY(type.getZT_DATA_KEY());
                assistCodeDto.setFZHS_LX_DATA_KEY(type.getFZHS_LX_DATA_KEY());
                assistCodeDto.setFZHS_PROJECT_BM(type.getFZHS_PROJECT_BM());
                assistCodeDto.setFZHS_PROJECT_MC(type.getFZHS_PROJECT_MC());
                assistCodeDto.setFZHS_FIELD_MAP(assistFieldsList);
                dataList.add(assistCodeDto);
            }
            Map<String, String> keyValueMap = new HashMap<>();
            keyValueMap.put("FIELD_KEY", type.getFIELD_KEY());
            keyValueMap.put("FIELD_VALUE", type.getFIELD_VALUE());
            assistCodeMap.get(type.getFZHS_PROJECT_BM()).add(keyValueMap);
        }

        int count = 0;
        if (dataList.size() == 0) {
            // 没数据的情况
            sendListData(codes, Collections.emptyList(), batchId, duijieQuery.getAccSet());
        }
        while (count < dataList.size()) {
            List<AssistCodeDto> subList = ListUtil.getSubList(dataList, count, count+1000);
            sendListData(subList, ListUtil.toSingleList(codes, AssistCode::getID), batchId, duijieQuery.getAccSet());

            count += 1000;
        }

        saveSendDataKeys(dataList, AssistCodeDto::getDATA_KEY);
    }

//    @Override
//    protected List<AssistCode> getNeedDeleteData(DuijieQuery duijieQuery) {
////        return repo.findAll(getDataQuerySpecification(OpType.DEL.getValue(), duijieQuery.getZtDataKey()));
//        return repo.getByZtDataKeyAndOpTypeAndSjjhbz(duijieQuery.getZtDataKey(), OpType.DEL.getValue(), Arrays.asList(SJJHBZ.WAITING.getValue(), SJJHBZ.ERROR.getValue()));
//    }

//    @Override
//    protected Specification<AssistCode> getDataQuerySpecification(Integer opTypeValue, String ztDataKey) {
//        return (root, criteriaQuery, criteriaBuilder) -> {
//            List<Predicate> ps = new ArrayList<>();
//            ps.add(criteriaBuilder.equal(root.get("ZT_DATA_KEY"), ztDataKey));
//            ps.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("sjjhbz"), SJJHBZ.WAITING.getValue()),
//                    criteriaBuilder.equal(root.get("sjjhbz"), SJJHBZ.ERROR.getValue())));
//            ps.add(criteriaBuilder.equal(root.get("opType"), opTypeValue));
//
//            criteriaQuery.where(ps.toArray(new Predicate[0]));
////            criteriaQuery.orderBy(criteriaBuilder.asc(root.get("id")));
//            return criteriaQuery.getRestriction();
//        };
//    }

    @Override
    protected String getCheckDuplicateGroupByFields() {
        return "DATA_KEY, FIELD_KEY";// 一个主表唯一 一个子表唯一
    }
}
